<template>
    <!-- 用于展示图片和视频文件详情的组件 -->
    <div class="media-window">
        <div class="win-title drag"></div>
        <div class="media-op no-drag">
            <div :class="['iconfont icon-large_arrow_left_line', currentIndex == 0 ? 'not-allow' : '']" @dblclick.stop
                title="上一个" @click="next(-1)"></div>
            <div :class="['iconfont icon-large_arrow_right_line', currentIndex >= mediaFileList.length - 1 ? 'not-allow' : '']"
                @dblclick.stop title="下一个" @click="next(1)"></div>
            <!-- 图片类可以放大缩小旋转等 -->
            <template v-if="fileList[0].fileType == 0 || fileList[0].fileType == 'IMAGE'">
                <el-divider direction="vertical"></el-divider>
                <div class="iconfont icon-fangda" @click.stop="changeSize(0.1)" @dblclick.stop title="放大"></div>
                <div class="iconfont icon-suoxiao" @click.stop="changeSize(-0.1)" @dblclick.stop title="缩小"></div>
                <div :class="['iconfont ', isOrigin ? 'icon-yuanshidaxiao' : 'icon-yuanshidaxiao1']" @dblclick.stop
                    @click="resize" :title="isOrigin ? '图片适应窗口大小' : '图片原始大小'"></div>
                <div class="iconfont icon-youxuanzhuan" @dblclick.stop @click="rotate" title="旋转"></div>
                <el-divider direction="vertical"></el-divider>
            </template>
            <!-- 下载按钮 -->
            <div class="iconfont icon-xiazai" @dblclick.stop @click="saveAs" title="另存为..."></div>
        </div>
        <div class="media-panel">
            <!-- 图片类 -->
            <viewer :options="options" @inited="inited" :images="fileList"
                v-if="(fileList[0].fileType == 0 || fileList[0].fileType == 'IMAGE') && (fileList[0].sendStatus == 1 || fileList[0].sendStatus == 'SENT')">
                <img :src="fileList[0].url" />
            </viewer>
            <!-- 视频类 -->
            <div ref="player" id="player"
                v-show="(fileList[0].fileType == 1 || fileList[0].fileType == 'VIDEO') && (fileList[0].sendStatus == 1 || fileList[0].sendStatus == 'SENT')"
                style="width: 100%; height: 100%;">
            </div>
            <!-- 文件类 -->
            <div class="file-panel"
                v-if="(fileList[0].fileType == 2 || fileList[0].fileType == 'OTHER') && (fileList[0].sendStatus == 1 || fileList[0].sendStatus == 'SENT')">
                <div class="file-item">文件名：{{ fileList[0].fileName }}</div>
                <div class="file-item">文件大小：{{ proxy.Utils.size2Str(fileList[0].fileSize) }}</div>
                <div class="file-item download">
                    <el-button type="primary" @click="saveAs">下载文件</el-button>
                </div>
            </div>
            <!-- 加载中 -->
            <div class="loading" v-if="fileList[0].sendStatus != 1 && fileList[0].sendStatus != 'SENT'">加载中...</div>
        </div>
        <WinOp @closeCallback="closeWin" :closeType="0"></WinOp>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch, onMounted, onUnmounted } from "vue"
import { useRoute, useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

/* 导入图片和视频工具 */
import 'viewerjs/dist/viewer.css'
import { component as Viewer } from 'v-viewer'
import DPlayer from "dplayer";

/* 图像工具初始化 */
const options = ref({
    inline: true,
    toolbar: false,
    navbar: false,
    button: false,
    title: false,
    zoomRatio: 0.1,
    zoomOnWheel: false,
})
const viewerMy = ref(null);
const inited = (e) => {
    viewerMy.value = e;
}

/* 视频工具初始化 */
const player = ref(null);  // 相当于在下面的初始化里写 element: document.getElementById('player')
const dPlayer = ref(null);
const initPlayer = () => {
    dPlayer.value = new DPlayer({
        element: player.value,
        theme: '#b7daff',
        screenshot: true,
        video: {
            url: '',
        },
    });
}

const currentIndex = ref(0);
const mediaFileList = ref([]);
const isOrigin = ref(true);
const fileList = ref([{ fileType: 0, sendStatus: 0, url: '' }]);

const serverPort = ref(10240);

const getUrl = (curFile) => {
    // 因为和存globalInfo的窗口不是同一个，所以没办法通过pinia获取到保存的serverPort
    // 所以通过主进程传递过来的初始化数据来获取serverPort，见下面的myApi.onNewWindowInit
    return `http://localhost:${serverPort.value}/file/` +
        `?fileId=${curFile.fileId}&partType=${curFile.partType}` +
        `&fileType=${curFile.fileType}&isCover=false&forceGet=${curFile.forceGet}` +  // isCover=false展示原图/原视频
        `&date=${new Date().getTime()}`;  // 防止文件被缓存
}

/* 获取当前查看的文件 */
const getCurrentFile = () => {
    // 进入函数时先暂停视频，防止上下切换文件调用该函数的时候之前的视频还在播放
    if (dPlayer.value) {
        dPlayer.value.pause();
    }

    const curFile = mediaFileList.value[currentIndex.value];
    // 获取url
    const url = getUrl(curFile)
    fileList.value.splice(0, 1, {
        url: url,
        fileType: curFile.fileType,
        sendStatus: 1,
        fileName: curFile.fileName,
        fileSize: curFile.fileSize,
        partType: curFile.partType,
        forceGet: curFile.forceGet
    });

    // 如果是视频，则加载视频
    if (curFile.fileType == 1 || curFile.fileType == 'VIDEO') {
        dPlayer.value.switchVideo({
            url: url,
        });
    }
}

/* 图像操作相关函数 */
const changeSize = (zoomRatio) => {
    if (!viewerMy.value) return;
    viewerMy.value.zoom(zoomRatio, true);
}
const resize = () => {
    if (!viewerMy.value) return;
    isOrigin.value = !isOrigin.value;
    if (isOrigin.value) {
        viewerMy.value.zoomTo(viewerMy.value.initialImageData.ratio, true);
    } else {
        viewerMy.value.zoomTo(1, true);
    }
}
const rotate = () => {
    if (!viewerMy.value) return;
    viewerMy.value.rotate(90);
}
const next = (index) => {
    if (currentIndex.value + index >= mediaFileList.value.length || currentIndex.value + index < 0) {
        return;
    }
    currentIndex.value += index;
    getCurrentFile();
}
const saveAs = () => {
    // 调用主进程下载文件
    const curFile = mediaFileList.value[currentIndex.value];
    myApi.saveAs({
        partType: curFile.partType,
        fileId: curFile.fileId
    })
}

const closeWin = () => {
    // 关闭时需要把DPlayer关闭，否则视频会一直播放
    if (dPlayer.value) {
        dPlayer.value.pause()
    }
}

/* 窗口创建时主进程发送了一个通信，把别的组件传递给主进程的数据发送了过来
   (Chat.vue里的showMediaDetailHandler函数中的myApi.openMediaDetailWindow --> 主进程)
   (主进程index.js中的window.webContents.send('newWindowInit', data) --> 渲染进程)
*/
myApi.onNewWindowInit((event, data) => {
    if (data.mediaFileList) mediaFileList.value = data.mediaFileList;
    if (data.serverPort) serverPort.value = data.serverPort;
    // 修改索引
    if (data.currentFileId != null) {
        // console.log(data.currentFileId);
        let index = mediaFileList.value.findIndex(item => item.fileId == data.currentFileId);
        currentIndex.value = index == -1 ? 0 : index;
    }
    // console.log(data)
    getCurrentFile();
})

const onWheel = (e) => {
    // 只有图像可以滚轮放大缩小
    if (fileList.value[0].fileType != 0 && fileList.value[0].fileType != 'IMAGE') return;
    if (e.deltaY < 0) {
        changeSize(0.1);
    } else {
        changeSize(-0.1);
    }
}

import { useAvatarInfoStore } from "@/stores/AvatarInfoStore";
const avatarInfoStore = useAvatarInfoStore()

myApi.onSetForceReload((event, data) => {
    avatarInfoStore.setForceReload(data.id, data.value)
})

onMounted(() => {
    // 滚轮滚动事件
    window.addEventListener('wheel', onWheel)
    // 播放器初始化
    initPlayer();
})
onUnmounted(() => {
    window.removeEventListener('wheel', onWheel)
    myApi.removeAllListeners('newWindowInit')
    myApi.removeAllListeners('setForceReload')
})
</script>

<style lang="scss" scoped>
.media-window {
    padding: 0px;
    height: calc(100vh);
    border: 1px solid#ddd;
    background: #fff;
    position: relative;
    overflow: hidden;

    .win-title {
        height: 37px;
    }

    .media-op {
        position: absolute;
        left: 0px;
        top: 0px;
        height: 35px;
        line-height: 35px;
        display: flex;
        align-items: center;

        .iconfont {
            font-size: 20px;
            padding: 0px 10px;

            &:hover {
                background: #f3f3f3;
                cursor: pointer;
            }
        }

        .not-allow {
            cursor: not-allowed;
            color: #ddd;
            text-decoration: none;

            &:hover {
                color: #ddd;
                cursor: not-allowed;
                background: none;
            }
        }
    }

    .media-panel {
        height: calc(100vh - 37px);
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;

        :deep(.viewer-backdrop) {
            background: #f5f5f5;
        }

        .file-panel {
            .file-item {
                margin-top: 5px;
            }

            .download {
                margin-top: 20px;
                text-align: center;
            }
        }
    }
}
</style>
